package com.example.shopping_li.goods;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.util.Log;
import android.view.FrameMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.shopping_li.Fragment.BaseFragment;
import com.example.shopping_li.R;
import com.example.shopping_li.URLUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

//商品页面碎片
public class GoodsFragment extends BaseFragment {
    ListView typLv;
    List<TypeBean.DataBean> data;
    TypeAdapter adapter;
    FragmentManager fm;

    @Override
    public void onCreate(@Nullable  Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fm=getChildFragmentManager();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_goods, container, false);
        typLv=view.findViewById(R.id.frag_goods_lv);
        //数据源
      data=new ArrayList<>();
//适配器
         adapter = new TypeAdapter( getContext(),data);
         typLv.setAdapter(adapter);
         //联网
        connectNet(URLUtils.allCategory);
        setItemClick();
        return view;
    }
private void setItemClick(){
        typLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //切换效果
                adapter.setSelPos(position);
                //切换右侧Fragment
                int cid=data.get(position).getId();//商品分类的ID
                changeFrag(cid);
            }
        });
}
    private void changeFrag(int cid){
        GoodsTypeFragment gtFrag = new GoodsTypeFragment();
        Bundle bundle=new Bundle();
        bundle.putInt("cid",cid);
        gtFrag.setArguments(bundle);
        FragmentTransaction tr=fm.beginTransaction();
        tr.replace(R.id.frag_goods_layout,gtFrag);//切换频繁replace
        tr.commit();
    }
    @Override
    public void onSuccess(String result) {
        Log.i("lsh12", "onSuccess: res==="+result);
        TypeBean bean=new Gson().fromJson(result,TypeBean.class);
        List<TypeBean.DataBean> list=bean.getData();
        data.addAll(list);
        adapter.notifyDataSetChanged();
        //显示右侧第一个数据
        int cid = data.get(0).getId();
        changeFrag(cid);

    }
}